//
//  YMAliYunUtil.m
//  YMMedical
//
//  Created by y s on 2023/6/29.
//

#import "YMAliYunUtil.h"
#import <AliyunOSSiOS/OSSService.h>

@interface YMAliYunUtil()

@property (nonatomic, strong) OSSClient *client;

@end

@implementation YMAliYunUtil

+ (instancetype)shared{
   static dispatch_once_t onceToken;
   static YMAliYunUtil *sharedInstance;
   dispatch_once(&onceToken, ^{
       sharedInstance = [[YMAliYunUtil alloc] init];
   });
   return sharedInstance;
}

- (instancetype)init{
   if (self = [super init]){
       
   }
   return self;
}


- (void)aliyunLaunch{
    NSString *endpoint = @"https://oss-cn-hangzhou.aliyuncs.com";
    // 移动端建议使用STS方式初始化OSSClient。
    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * _Nullable{
        OSSFederationToken *token = [OSSFederationToken new];
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        token.tAccessKey = Aliyun_Oss_Access_key;
        token.tSecretKey = Aliyun_Oss_Secret_key;
        return token;
    }];

    self.client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
}

- (void)aliyunUploadFile:(NSData *)fileData
                fileName:(NSString *)fileName
                 success:(void(^)(NSString *strUrl))success
                 failure:(void(^)(void))failure{
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = @"home-detection";
    put.objectKey = fileName;
    // 直接上传NSData。
    put.uploadingData = fileData;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask *putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            if (success){
                NSString *backUrl = [NSString stringWithFormat:@"https://home-detection.oss-cn-hangzhou.aliyuncs.com/%@",fileName];
                success(backUrl);
            }
        } else {
            if (failure){
                failure();
            }
        }
        return nil;
    }];
    // 等待任务完成。
    // [putTask waitUntilFinished];
}




@end
